import checkbox from './components/checkbox.vue';
import control from './components/control.vue';

const getEventName = (type, name) => name ? `${ type }.${ name }` : type;

export default {
    props: {
        player: {
            type: Object
        }
    },
    data() {
        return {
            eventKeys: {}
        };
    },
    components: {
        checkbox, control
    },
    computed: {
        room: function() {
            return this.player && this.player.room;
        },
        creator: function() {
            return this.room && this.room.creator.id === this.player.id;
        },
        game: function() {
            return this.room && this.room.game;
        },
        board: function() {
            return this.game && this.game.board;
        },
        role() {
            return this.player && this.player.role;
        },
        team() {
            return this.room && this.role && this.room.teams[this.role.team];
        },
        group: function () {
            return this.game && this.role && this.game.groups[this.role.group];
        },
        result: function() {
            return this.role && this.role.result;
        }
    },
    created() {
        if (this.$root !== this) {
            this.$root.$on('resize', () => this.resize && this.resize());
            this.$root.$on('key.start', keyInfo => this.invoke('key.start', keyInfo.name, keyInfo));
            this.$root.$on('key.start.repeat', keyInfo => this.invoke('key.start.repeat', keyInfo.name, keyInfo));
            this.$root.$on('key.press', keyInfo => this.invoke('key.press', keyInfo.name, keyInfo));
            this.$root.$on('key.end', keyInfo => this.invoke('key.end', keyInfo.name, keyInfo));
            this.$root.$on('control.start', control => this.invoke('control.start', control.name, control));
            this.$root.$on('control.end', control => this.invoke('control.end', control.name, control));
            this.$root.$on('control.press', control => this.invoke('control.press', control.name, control));
        }
    },
    beforeDestroy() {
        if (this.$root !== this) {
            this.$root.$off([
                'resize',
                'key.start',
                'key.start.repeat',
                'key.press',
                'key.end',
                'control.start',
                'control.end',
                'control.press',
            ])
        }
    },
    methods: {
        invoke(type, name, info) {
            let eventName = getEventName(type, name);
            let keys = this.eventKeys[eventName];
            if (!keys) {
                let reg = new RegExp(`(^|,)(${ eventName }|${ type })($|,)`, 'ig');
                keys = Object.keys(this).filter(key => !key.startsWith('$') && reg.test(key));
                this.eventKeys[eventName] = keys;
            }
            for (let key of keys) {
                this[key] && this[key](info);
            }
        }
    }
}